package com.orion.config;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * 形成一个单独的组件
 * <p>
 * 将自定义的VerifyCodeAuthenticationFilter和自定义的VerifyCodeAuthenticationProvider绑定在一块
 *
 * @author Administrator
 * @date 2021/9/13
 */
@Component("verifyCodeSecurityConfig")
public class VerifyCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {


    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {

        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setDefaultTargetUrl("/index");


        AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler("/myLogin?error");


        VerifyCodeAuthenticationFilter verifyCodeAuthenticationFilter = new VerifyCodeAuthenticationFilter();
        verifyCodeAuthenticationFilter.setAuthenticationManager(httpSecurity.getSharedObject(AuthenticationManager.class));

        verifyCodeAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        verifyCodeAuthenticationFilter.setAuthenticationFailureHandler(failureHandler);

        VerifyCodeAuthenticationProvider verifyCodeAuthenticationProvider = new VerifyCodeAuthenticationProvider();

        httpSecurity.authenticationProvider(verifyCodeAuthenticationProvider)
                .addFilterBefore(verifyCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
